package com.chushouya.product.service.api.impl;

import com.chushouya.product.dto.api.evaluate.*;
import com.general.framework.core.lang.*;
import com.chushouya.common.dto.suhuishou.ResponseDTO;
import com.chushouya.common.support.Contexts;
import com.chushouya.common.util.SuhuishouRequest;
import com.general.framework.core.exception.Ex;
import com.chushouya.product.constants.EvaluateTipTypeEnum;
import com.chushouya.product.constants.EvaluateTypeEnum;
import com.chushouya.product.dao.entity.EvaluateLogEntity;
import com.chushouya.product.dao.entity.EvaluateTipsEntity;
import com.chushouya.product.dao.entity.ProductEntity;
import com.chushouya.product.dao.repository.EvaluateLogRepository;
import com.chushouya.product.dao.repository.EvaluateTipsRepository;
import com.chushouya.product.dao.repository.ProductRepository;
import com.chushouya.product.dto.api.evaluatetips.EvaluateTipsQuery;
import com.chushouya.product.dto.api.suhuishou.SuhuishouEvaluateItemDTO;
import com.chushouya.product.dto.api.suhuishou.SuhuishouEvaluateProductDTO;
import com.chushouya.product.dto.api.suhuishou.SuhuishouEvaluateResultDTO;
import com.chushouya.product.rabbitmq.sender.ResolveEvaluateMessageSender;
import com.chushouya.product.service.api.EvaluateApiService;
import com.general.framework.data.redis.RedisCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.chushouya.common.constant.SuhuishouConstants.*;


/**
 * @author wangweibo
 */
@Slf4j
@Service
public class EvaluateApiServiceImpl implements EvaluateApiService {


    @Resource
    private ProductRepository productRepository;

    @Resource
    private EvaluateLogRepository evaluateLogRepository;

    @Resource
    private EvaluateTipsRepository evaluateTipsRepository;

    @Resource
    private SuhuishouRequest suhuishouRequest;

    @Resource
    private ResolveEvaluateMessageSender resolveEvaluateMessageSender;

    @Resource
    private RedisCache redisCache;

    /**
     * 速回收订单状态
     */
    private static final Integer SUHUISHOU_HTTP_STATUS = 200;

    /**
     * 缓存键前缀
     */
    private static final String CACHE_KEY_EVALUATE_PRODUCT = "evaluate:product:";
    private static final String CACHE_KEY_EVALUATE_ITEM = "evaluate:item:";


    private ProductEntity getProduct(Long productId) {
        ProductEntity productEntity = productRepository.selectByPrimaryKey(productId);
        Validate.isNull(productEntity, "商品不存在");
        return productEntity;
    }

    private List<EvaluateTipsEntity> getEvaluateTips() {
        EvaluateTipsQuery query = new EvaluateTipsQuery();
        return evaluateTipsRepository.selectList(query);
    }

    /**
     * 计算到当天23:59:59的秒数
     * @return 剩余秒数
     */
    private long getSecondsUntilEndOfDay() {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime endOfDay = now.with(LocalTime.MAX); // 23:59:59.999999999
        long seconds = java.time.Duration.between(now, endOfDay).getSeconds();
        // 确保至少有1秒的过期时间
        return seconds > 0 ? seconds : 1;
    }

    @Override
    public EvaluateProductApiDTO evaluateProduct(EvaluateProductRequestApiDTO request) {
        final Long productId = request.getProductId();
        
        // 尝试从缓存获取
        String cacheKey = CACHE_KEY_EVALUATE_PRODUCT + productId;
        EvaluateProductApiDTO cachedResult = redisCache.getCacheObject(cacheKey);
        if (Objects.nonNull(cachedResult)) {
            log.info("从缓存获取商品评估信息，商品ID: {}", productId);
            return cachedResult;
        }
        
        // 缓存未命中，查询数据
        log.info("缓存未命中，查询商品评估信息，商品ID: {}", productId);
        ProductEntity productEntity = getProduct(productId);
        final Map<String, Object> params = new HashMap<>();
        params.put("productId", productEntity.getSuProductId());
        ResponseDTO<SuhuishouEvaluateProductDTO> response = suhuishouRequest.httpRequest(SUHUISHOU_EVALUATE_PRODUCT, "GET", params, SuhuishouEvaluateProductDTO.class);
        EvaluateProductApiDTO evaluateProductDTO = Beans.copy(productEntity, EvaluateProductApiDTO.class);
        List<EvaluateListApiDTO> skuList = Jsons.parseArray(Jsons.toJsonString(response.getData().getSkuList()), EvaluateListApiDTO.class);
        skuList.forEach(item -> item.setEvaluateType(EvaluateTypeEnum.SKU.value()));
        handleEvaluateTips(skuList);
        evaluateProductDTO.setEvaluateList(skuList);
        
        // 存入缓存（过期时间为当天23:59:59）
        long expireSeconds = getSecondsUntilEndOfDay();
        redisCache.setCacheObject(cacheKey, evaluateProductDTO, expireSeconds, TimeUnit.SECONDS);
        log.info("商品评估信息已缓存，商品ID: {}, 缓存键: {}, 过期时间: {}秒（当天23:59:59）", productId, cacheKey, expireSeconds);
        
        // 发送异步解析消息
        resolveEvaluateMessageSender.sendResolveEvaluateMessage(productId);
        
        return evaluateProductDTO;
    }

    @Override
    public EvaluateItemApiDTO evaluateItem(EvaluateItemRequestApiDTO request) {
        final Long productId = request.getProductId();
        final String skuCode = request.getSkuCode();
        
        // 尝试从缓存获取
        String cacheKey = CACHE_KEY_EVALUATE_ITEM + productId + ":" + skuCode;
        EvaluateItemApiDTO cachedResult = redisCache.getCacheObject(cacheKey);
        if (Objects.nonNull(cachedResult)) {
            log.info("从缓存获取商品评估项信息，商品ID: {}, SKU编码: {}", productId, skuCode);
            return cachedResult;
        }
        
        // 缓存未命中，查询数据
        log.info("缓存未命中，查询商品评估项信息，商品ID: {}, SKU编码: {}", productId, skuCode);
        ProductEntity productEntity = getProduct(productId);
        final Map<String,Object> params = new HashMap<>();
        params.put("productId",productEntity.getSuProductId());
        params.put("skuCode",skuCode);
        ResponseDTO<SuhuishouEvaluateItemDTO> response = suhuishouRequest.httpRequest(SUHUISHOU_EVALUATE_ITEM, "GET", params, SuhuishouEvaluateItemDTO.class);
        final Integer code = response.getCode();
        Validate.isFalse(SUHUISHOU_HTTP_STATUS.equals(code), response.getMsg());
        EvaluateItemApiDTO evaluateItemDTO = new EvaluateItemApiDTO();
        evaluateItemDTO.setProductId(productId);
        evaluateItemDTO.setSkuId(response.getData().getSkuId());
        List<EvaluateListApiDTO> evaluateList = Jsons.parseArray(Jsons.toJsonString(response.getData().getEvaluateList()), EvaluateListApiDTO.class);
        evaluateList.forEach(item -> item.setEvaluateType(EvaluateTypeEnum.ITEM.value()));
        handleEvaluateTips(evaluateList);
        evaluateItemDTO.setEvaluateList(evaluateList);
        
        // 存入缓存（过期时间为当天23:59:59）
        long expireSeconds = getSecondsUntilEndOfDay();
        redisCache.setCacheObject(cacheKey, evaluateItemDTO, expireSeconds, TimeUnit.SECONDS);
        log.info("商品评估项信息已缓存，商品ID: {}, SKU编码: {}, 缓存键: {}, 过期时间: {}秒（当天23:59:59）", 
                productId, skuCode, cacheKey, expireSeconds);
        
        return evaluateItemDTO;
    }

    @Override
    public List<EvaluateListApiDTO> productEvaluateList(Long productId) {
        EvaluateProductRequestApiDTO request = new EvaluateProductRequestApiDTO();
        request.setProductId(productId);
        // 获取商品信息
        EvaluateProductApiDTO evaluateProductDTO = getEvaluateProductInfo(request);
        
        // 获取估价项信息
        EvaluateItemApiDTO evaluateItemDTO = getEvaluateItemInfo(productId, evaluateProductDTO.getEvaluateList());
        
        // 合并SKU属性和估价项信息
        return mergeEvaluateList(evaluateProductDTO.getEvaluateList(), evaluateItemDTO.getEvaluateList());
    }
    /**
     * 设置选项的tipsData
     */
    private void handleEvaluateTips(List<EvaluateListApiDTO> evaluateList) {
        List<EvaluateTipsEntity> evaluateTipsList = this.getEvaluateTips();
        if (Lists.isEmpty(evaluateTipsList) || Lists.isEmpty(evaluateList)) {
            return;
        }
        List<EvaluateTipsEntity> evaluateQuestionTipsList = evaluateTipsList.stream()
                .filter(tips -> EvaluateTipTypeEnum.QUESTION.value().equals(tips.getTipsType()))
                .collect(Collectors.toList());

        List<EvaluateTipsEntity> evaluateAnswerList = evaluateTipsList.stream()
                .filter(tips -> EvaluateTipTypeEnum.ANSWER.value().equals(tips.getTipsType()))
                .collect(Collectors.toList());

        evaluateList.forEach(evaluate -> {
            EvaluateTipsEntity evaluateTipsEntity = evaluateQuestionTipsList.stream()
                    .filter(tips -> tips.getAttrName().equals(evaluate.getAttrName()))
                    .findFirst()
                    .orElse(null);
            if(Objects.nonNull(evaluateTipsEntity)) {
                evaluate.setTipsData(Jsons.parseObject(evaluateTipsEntity.getTipsData(), TipsDataDTO.class));
            }
        });
        evaluateList.forEach(evaluate -> {
            List<EvaluateValueApiDTO> evaluateValues = evaluate.getAttrValues();
            if (Objects.nonNull(evaluateValues)) {
                evaluateValues.forEach(value -> {
                    EvaluateTipsEntity tipsEntity = evaluateAnswerList.stream()
                            .filter(tips -> tips.getAttrValueName().equals(value.getValueContent()))
                            .findFirst()
                            .orElse(null);
                    if (Objects.nonNull(tipsEntity)) {
                        value.setTipsData(Jsons.parseObject(tipsEntity.getTipsData(), TipsDataDTO.class));
                    }
                });
            }
        });

    }
    
    /**
     * 获取商品估价信息
     */
    private EvaluateProductApiDTO getEvaluateProductInfo(EvaluateProductRequestApiDTO request) {
        EvaluateProductApiDTO evaluateProductDTO = this.evaluateProduct(request);
        if (Objects.isNull(evaluateProductDTO)) {
            throw Ex.business("商品信息不存在，商品ID: " + request.getProductId());
        }
        return evaluateProductDTO;
    }
    
    /**
     * 获取估价项信息
     */
    private EvaluateItemApiDTO getEvaluateItemInfo(Long productId, List<EvaluateListApiDTO> skuList) {
        final String skuCode = this.getOneSkuCode(skuList);
        EvaluateItemRequestApiDTO requestApiDTO = new EvaluateItemRequestApiDTO();
        requestApiDTO.setProductId(productId);
        requestApiDTO.setSkuCode(skuCode);
        
        EvaluateItemApiDTO evaluateItemDTO = this.evaluateItem(requestApiDTO);
        if (Objects.isNull(evaluateItemDTO)) {
            throw Ex.business("商品估价信息不存在，商品ID: " + productId + ", SKU编码: " + skuCode);
        }
        return evaluateItemDTO;
    }
    
    /**
     * 合并SKU属性列表和估价项列表
     */
    private List<EvaluateListApiDTO> mergeEvaluateList(List<EvaluateListApiDTO> skuAttrList,
                                                       List<EvaluateListApiDTO> evaluateItemList) {
        List<EvaluateListApiDTO> result = Lists.newArrayList();
        
        // 处理SKU属性列表
        if (!Lists.isEmpty(skuAttrList)) {
            List<EvaluateListApiDTO> skuEvaluateList = skuAttrList.stream()
                    .map(this::convertSkuToEvaluateList)
                    .collect(Collectors.toList());
            skuEvaluateList.stream().forEach(sku -> sku.setEvaluateType(EvaluateTypeEnum.SKU.value()));
            result.addAll(skuEvaluateList);
        }
        
        // 处理估价项列表
        if (!Lists.isEmpty(evaluateItemList)) {
            List<EvaluateListApiDTO> itemEvaluateList = evaluateItemList.stream()
                    .map(this::convertItemToEvaluateList)
                    .collect(Collectors.toList());
            itemEvaluateList.stream().forEach(item -> item.setEvaluateType(EvaluateTypeEnum.ITEM.value()));
            result.addAll(itemEvaluateList);
        }
        
        return result;
    }
    
    /**
     * 将SKU属性转换为估价列表项
     */
    private EvaluateListApiDTO convertSkuToEvaluateList(EvaluateListApiDTO skuAttr) {
        EvaluateListApiDTO evaluateListDTO = new EvaluateListApiDTO();
        evaluateListDTO.setAttrId(skuAttr.getAttrId());
        evaluateListDTO.setAttrName(skuAttr.getAttrName());
        evaluateListDTO.setIsMultiSelect(Boolean.FALSE);
        List<EvaluateValueApiDTO> attrValues = Lists.newArrayList();
        for (Object attrValue : skuAttr.getAttrValues()) {
            EvaluateValueApiDTO evaluateValue = new EvaluateValueApiDTO();
            
            // 手动赋值，避免Beans.copy设置null值
            if (attrValue instanceof SkuValueApiDTO) {
                SkuValueApiDTO skuValue = (SkuValueApiDTO) attrValue;
                evaluateValue.setValueId(skuValue.getValueId());
                evaluateValue.setValueContent(skuValue.getValueContent());
                // 不设置tipsData，保持为null，让序列化时忽略
            } else {
                // 使用Beans.copy作为fallback，但不设置tipsData
                evaluateValue = Beans.copy(attrValue, EvaluateValueApiDTO.class);
            }
            
            attrValues.add(evaluateValue);
        }
        evaluateListDTO.setAttrValues(attrValues);
        
        return evaluateListDTO;
    }
    
    /**
     * 将估价项转换为估价列表项
     */
    private EvaluateListApiDTO convertItemToEvaluateList(EvaluateListApiDTO evaluateItem) {
        EvaluateListApiDTO evaluateListDTO = new EvaluateListApiDTO();
        evaluateListDTO.setAttrId(evaluateItem.getAttrId());
        evaluateListDTO.setAttrName(evaluateItem.getAttrName());
        evaluateListDTO.setIsMultiSelect(evaluateItem.getIsMultiSelect());
        
        List<EvaluateValueApiDTO> evaluateValues = Lists.newArrayList();
        for (EvaluateValueApiDTO attrValue : evaluateItem.getAttrValues()) {
            EvaluateValueApiDTO evaluateValue = new EvaluateValueApiDTO();
            evaluateValue.setValueId(attrValue.getValueId());
            evaluateValue.setValueContent(attrValue.getValueContent());
            evaluateValues.add(evaluateValue);
        }
        evaluateListDTO.setAttrValues(evaluateValues);
        
        return evaluateListDTO;
    }

    private String getOneSkuCode(List<EvaluateListApiDTO> skuAttrList) {
        if (Lists.isEmpty(skuAttrList)) {
            return Strings.EMPTY;
        }
        log.info("====>获取商品SKU编码：{}", skuAttrList);
        skuAttrList.sort(Comparator.comparing(EvaluateListApiDTO::getAttrId));
        StringBuilder builder = new StringBuilder();
        
        for (EvaluateListApiDTO attr : skuAttrList) {
            // 检查属性值列表是否为空
            if (attr.getAttrValues() == null || attr.getAttrValues().isEmpty()) {
                log.warn("SKU属性值列表为空，跳过属性ID: {}", attr.getAttrId());
                continue;
            }
            
            // 获取第一个属性值
            EvaluateValueApiDTO firstValue = attr.getAttrValues().get(0);
            if (firstValue == null) {
                log.warn("SKU属性值为空，跳过属性ID: {}", attr.getAttrId());
                continue;
            }
            
            // 安全获取valueId
            Long valueId = firstValue.getValueId();
            
            if (valueId != null) {
                if (builder.length() > 0) {
                    builder.append(",");
                }
                builder.append(Strings.format("{}:{}", attr.getAttrId(), valueId));
            }
        }
        
        String result = builder.toString();
        log.info("====>生成的SKU编码: {}", result);
        return result;
    }

    @Override
    public EvaluateResultApiDTO evaluateResult(EvaluateRequestApiDTO request) {
        final Long productId = request.getProductId();
        final String skuCode = request.getSkuCode();
        final Long skuId = request.getSkuId();
        final String evaluateCode = request.getEvaluateCode();
        ProductEntity productEntity = getProduct(productId);
        final Map<String,Object> params = new HashMap<>();
        params.put("productId",productEntity.getSuProductId());
        params.put("skuCode",skuCode);
        params.put("skuId",skuId);
        params.put("evaluateCode",evaluateCode);
        ResponseDTO<SuhuishouEvaluateResultDTO> response = suhuishouRequest.httpRequest(SUHUISHOU_EVALUATE_RESULT, "POST", params, SuhuishouEvaluateResultDTO.class);
        EvaluateResultApiDTO evaluateResultDTO = Beans.copy(response.getData(), EvaluateResultApiDTO.class);
        evaluateResultDTO.setProductId(productId);
        evaluateResultDTO.setProductImage(productEntity.getProductImage());
        evaluateResultDTO.setEvaluateId(Strings.format("{}", response.getData().getEvaluateId()));
        log.info("====>估价结果：{}", evaluateResultDTO);
        this.saveEvaluate(evaluateResultDTO,request,productEntity);
        return evaluateResultDTO;
    }

    /**
     * 保存估价信息
     */
    private void saveEvaluate(EvaluateResultApiDTO evaluateResultDTO,EvaluateRequestApiDTO request,ProductEntity productEntity) {
        log.info("====>估价结果：{}", Jsons.toFormatJsonString(evaluateResultDTO));
        log.info("====>估价结果：{}", Jsons.toFormatJsonString(Contexts.getHeaderContext()));
        final String platform = Contexts.getHeaderContext().getPlatform() ;
        final Long userId = Contexts.getUserContext().getUserId();
        EvaluateLogEntity evaluateEntity = Beans.copy(evaluateResultDTO, EvaluateLogEntity.class);
        evaluateEntity.setEvaluateId(Strings.format("{}", evaluateResultDTO.getEvaluateId()));
        evaluateEntity.setPlatform(platform);
        evaluateEntity.setPartnerId(Contexts.getHeaderContext().getPartnerId());
        evaluateEntity.setUserId(userId);
        evaluateEntity.setBrandId(productEntity.getBrandId());
        evaluateEntity.setCategoryId(productEntity.getCategoryId());
        evaluateEntity.setSeriesId(productEntity.getSeriesId());
        evaluateEntity.setEvaluateItem(Jsons.toJsonString(evaluateResultDTO.getEvaluateItems()));
        evaluateEntity.setEvaluateCode(request.getEvaluateCode());
        evaluateEntity.setSkuCode(request.getSkuCode());
        evaluateEntity.setSkuId(request.getSkuId());
        evaluateEntity.setSuProductId(productEntity.getSuProductId());
        evaluateLogRepository.insertSelective(evaluateEntity);
    }



    @Override
    public EvaluateLogEntity getEvaluateInfo(String EvaluateId) {
        return evaluateLogRepository.selectByEvaluateNo(EvaluateId);
    }
}
